<template>
    <el-dialog class="elDialog" ref="dialogform" :title="addEditName + title" :visible.sync="dialogVisible"
        :width="addEditFlag == 'add' ? '50%' : '90%'" :before-close="handleClose" v-loading="loading">
        <el-form v-if="addEditFlag == 'add'" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px"
            class="demo-ruleForm">

            <el-row :gutter="15">
                <el-col :span="12">
                    <el-form-item label="报告名称" prop="reportName">
                        <el-input v-model="ruleForm.reportName" maxlength="20" show-word-limit class="w100p" clearable
                            placeholder="请输入报告名称"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="报告类型" prop="reportType">
                        <el-select v-model="ruleForm.reportType" filterable clearable class="w100p">
                            <el-option v-for="(item, index) in reportTypeList" :key="index" :label="item.name"
                                :value="item.reportType" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="记录人" prop="staffId">
                        <el-select v-model="ruleForm.staffId" filterable clearable class="w100p"
                            @change="handleChangeStaff">
                            <el-option v-for="item, index in staffList" :key="index" :label="item.staffName"
                                :value="item.staffId" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="选择时间" prop="uploadDateTime">
                        <el-date-picker v-model="ruleForm.uploadDateTime" value-format="yyyy-MM-dd HH:mm:ss"
                            type="datetime" placeholder="选择时间" :picker-options="pickerOptions" class="w100p">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item label="上传文件" prop="reportFileIdList">
                <UpLoadFiles v-if="dialogVisible" @getFileIdList="getFileIdList" :limit="6"
                    :accept="'.png, .jpg, .jpeg, .pdf'" :idList="reportFileIdList">
                </UpLoadFiles>
            </el-form-item>
        </el-form>
        <div class="fileContent" v-if="fileSrcList.length > 0">
            <div class="fileList">
                <div class="file" :class="fileIndex == index ? 'fileActive' : 'file'" v-for="file, index in fileSrcList"
                    :key="index" @click="chooseFile(file, index)">
                    <img class="img" v-if="file.type.indexOf('pdf') !== -1" src="@/assets/pdf.png" alt="">
                    <img class="img" v-else :src="file.url" alt="">
                </div>
            </div>
            <div class="content">
                <iframe class="iframe" v-if="fileSrcList[fileIndex].type.indexOf('pdf') !== -1"
                    :src="`${fileSrcList[fileIndex].url}`" style="width:100%; height:100%;"></iframe>
                <el-image style="width:100%; height:100%;" :src="fileSrcList[fileIndex].url"
                    :fit="'scale-down'"></el-image>
            </div>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submitForm" v-show="addEditFlag == 'add'">确 定</el-button>
        </span>
    </el-dialog>
</template>
<script>
import qualityMonitoringReportManagement from '@/api/quality-management/quality-monitoring-report-management.js';
import UpLoadFiles from "@/components-production-management/UpLoadFiles";
import fileUpload from '@/api/file.js';

export default {
    components: { UpLoadFiles },
    props: {
        addEditFlag: {
            type: String,
            default: () => {
                return 'add'
            }
        },
        data: {
            type: Object,
            default: () => {
                return {}
            }
        },
        title: {
            type: String,
            default: () => {
                return '操作表单'
            }
        },
        dialogVisible: {
            type: Boolean,
            default: () => {
                return false
            }
        },
        staffList: {
            type: Array,
            default: () => {
                return []
            }
        },
    },
    data() {
        return {
            loading: false,
            fileIndex: 0,
            addEditName: '添加',
            addEditApi: '',
            ruleForm: {},
            reportFileIdList: [],
            fileSrcList: [],
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() > Date.now();
                },
                shortcuts: [{
                    text: '今天',
                    onClick(picker) {
                        picker.$emit('pick', new Date());
                    }
                }, {
                    text: '昨天',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24);
                        picker.$emit('pick', date);
                    }
                }, {
                    text: '一周前',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', date);
                    }
                }]
            },
            reportTypeList: [
                { name: "水质检测报告", id: 0, reportType: "WATERQUALITYMONITORING" },
                { name: "质量自检报告", id: 1, reportType: "QUALITYSELFINSPECTION" },
                { name: "质量法检报告", id: 2, reportType: "QUALITYINSPECTION" },
            ],
            rules: {
                reportFileIdList: [
                    { required: true, message: '请上传文件', trigger: 'change' }
                ],
                reportName: [
                    { required: true, message: '请上传报告名称', trigger: 'change' }
                ],
                reportType: [
                    { required: true, message: '请选择报告类型', trigger: 'change' }
                ],
                staffId: [
                    { required: true, message: '请选择操作人', trigger: 'change' }
                ],
                uploadDateTime: [
                    { required: true, message: '请选择上传时间', trigger: 'change' }
                ],
            }
        }
    },
    watch: {
        dialogVisible(v) {
            v && this.initData()
        }
    },
    mounted() { },
    methods: {
        initData() {
            this.reportFileIdList = [];
            this.fileSrcList = [];
            if (this.addEditFlag == 'add') {
                this.resetForm()
                this.addEditApi = qualityMonitoringReportManagement.add
                this.addEditName = '添加';
                this.getInitRulFormData();
            } else if (this.addEditFlag == 'edit') {
                this.ruleForm = { ...this.data }
                this.addEditApi = qualityMonitoringReportManagement.edit;
                this.reportFileIdList = this.data.reportFileIdList || [];
                this.loading = true;
                this.reportFileIdList.forEach(async (id, index) => {
                    fileUpload.download(id).then(async res => {
                        this.loading = false;
                        let { data } = res;
                        this.$set(this.fileSrcList, index, {
                            url: `${this.$baseurl.fileServiceUrl}base/files/preview?fileId=${id}`,
                            type: data.type
                        })
                    }).catch(err => {
                        this.loading = false;
                    })
                });
                this.addEditName = '预览'
            }
        },
        getFileIdList(data) {
            console.log(data)
            this.$set(this.ruleForm, 'reportFileIdList', data.fileIdList || [])
        },
        chooseFile(file, index) {
            this.fileIndex = index
        },
        //初始化一些表单数据
        getInitRulFormData() {
            let id = sessionStorage.getItem('staffId') || null;
            let params = {
                staffId: id == 'null' ? '' : Number(id),
                uploadDateTime: this.$formatTime(new Date(), 'yyyy-MM-dd HH:mm:ss')
            }
            this.$set(this, 'ruleForm', params);
        },
        //获取姓名
        handleChangeStaff(id) {
            let rut = this.staffList.find(item => item.staffId == id);
            let staffName = rut?.staffName
            this.$set(this.ruleForm, 'staffName', staffName || '');
        },
        //提交表单
        submitForm() {
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    this.addEditApi({ ...this.ruleForm }).then(res => {
                        let msg = res.success ? '操作成功' : '操作失败'
                        this.$message[res.success ? 'success' : 'warning'](res.msg || msg)
                        res.success && this.cancel();
                    }).catch(err => {
                        console.log(err)
                    })
                } else {
                    return false;
                }
            })
        },
        //重置
        resetForm() {
            this.ruleForm = {};
            this.$refs.ruleForm && this.$refs.ruleForm.resetFields()
        },
        //取消关闭
        cancel() {
            this.resetForm()
            this.$emit("closeDialog")
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => { this.resetForm(); this.cancel() })
                .catch(_ => { });
        }
    }
};
</script>
<style lang="scss" scoped>
.elDialog {
    ::v-deep .el-dialog {
        margin-top: 5vh !important;
    }
}

.fileContent {
    width: 100%;
    display: flex;
    justify-content: space-between;

    .fileList {
        width: 120px;
        height: 100%;

        .file {
            width: 120px;
            height: 120px;
            border-radius: 15px;
            margin-bottom: 10px;
            background: #cecece;
            overflow: hidden;
            position: relative;

            .iframe {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }

            .img {
                width: 100%;
                height: 100%;
            }
        }

        .fileActive {
            border: 5px solid #0ca0ea;
            box-shadow: 0px 0px 10px 0px #707070;
        }
    }

    .content {
        width: calc(100% - 140px);
        height: 700px;
        border: 1px solid #cecece;
        background-color: #cecece;
        overflow: hidden;

        .img {
            width: 100%;
            height: 100%;
        }
    }
}
</style>